var layer
function getCurrentLocation() {
    return new Promise((resolve, reject) => {
        // 检查浏览器是否支持Geolocation API
        if (!navigator.geolocation) {
            reject(new Error('您的浏览器不支持地理位置功能'));
            return;
        }

        // 获取当前位置
        navigator.geolocation.getCurrentPosition(
            // 成功回调
            (position) => {
                const latitude = position.coords.latitude;  // 纬度
                const longitude = position.coords.longitude; // 经度
                const accuracy = position.coords.accuracy;   // 精度（米）

                resolve({
                    latitude: latitude,
                    longitude: longitude,
                    accuracy: accuracy,
                    timestamp: position.timestamp
                });
            },
            // 错误回调
            (error) => {
                let errorMessage;
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = '用户拒绝提供地理位置权限';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = '无法获取当前位置信息';
                        break;
                    case error.TIMEOUT:
                        errorMessage = '获取位置信息超时';
                        break;
                    default:
                        errorMessage = '发生未知错误';
                        break;
                }
                reject(new Error(errorMessage));
            },
            // 选项配置
            {
                enableHighAccuracy: true,    // 高精度模式
                timeout: 10000,              // 超时时间（10秒）
                maximumAge: 60000            // 缓存位置的最大年龄（60秒）
            }
        );
    });
}
document.addEventListener('DOMContentLoaded', function() {
    getCurrentLocation()
        .then(location => {
            console.log('成功获取当前位置:', location);
            $.cookie('longitude', location.longitude)
            $.cookie('latitude', location.latitude)
        })

    $.ajax({
        url: '/user/findByName',
        type: 'post',
        data:{
            username: $.cookie('username')
        },
        success: function(res) {
            if (res.code === 200) {
                const userProfile = document.getElementById('userProfile');
                const username = document.querySelector('.username');
                const avatar = document.querySelector('.user-avatar');
                username.textContent = res.data.username;
                avatar.src = res.data.icon;
                var isOwner = res.data.isOwner;
                if (isOwner === 1) {
                    document.querySelector(".become-owner-btn").style.display = "none"
                    document.querySelector(".overviewShops").style.display = "block"
                }
            }
        },
        error: function(xhr, status, error) {}
    })

    const mobileMenuBtn = document.getElementById('mobileMenuBtn');
    const navMenu = document.getElementById('navMenu');

    mobileMenuBtn.addEventListener('click', function() {
        navMenu.classList.toggle('active');
    });

    const userProfile = document.getElementById('userProfile');
    const userDropdown = document.getElementById('userDropdown');

    userProfile.addEventListener('click', function(e) {
        e.stopPropagation();
        userDropdown.classList.toggle('active');
    });

    document.addEventListener('click', function() {
        userDropdown.classList.remove('active');
        navMenu.classList.remove('active');
    });
    // 个人中心显示
    document.querySelector(".personalInformation").addEventListener("click",function (){
        location.href="/userInformation"
    })

    const contentFrame = document.getElementById('contentFrame');
    const iframeLoading = document.getElementById('iframeLoading');

    contentFrame.addEventListener('loadstart', function() {
        iframeLoading.style.display = 'flex';
    });

    contentFrame.addEventListener('load', function() {
        iframeLoading.style.display = 'none';

        const currentSrc = contentFrame.src.split('/').pop();
        const navLinks = document.querySelectorAll('.nav-link');

        navLinks.forEach(link => {
            const linkSrc = link.getAttribute('data-src');
            if (linkSrc === currentSrc) {
                navLinks.forEach(l => l.classList.remove('active'));
                link.classList.add('active');
            }
        });

        // 存储当前子页面到sessionStorage
        sessionStorage.setItem('currentPage', currentSrc);
    });

    const navLinks = document.querySelectorAll('.nav-link');

    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            navMenu.classList.remove('active');

            navLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');

            const page = this.getAttribute('data-src');
            contentFrame.src = page;
        });
    });

    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            navMenu.classList.remove('active');
        }
    });
    const becomeOwnerBtn = document.querySelector('.become-owner-btn');

    // 2. 绑定点击事件，弹出确认弹框
    becomeOwnerBtn.addEventListener('click', function() {
        location.href="/UserOwnerApplication"
    });


    // 页面加载时，检查sessionStorage中是否有保存的子页面
    const savedPage = sessionStorage.getItem('currentPage');
    if (savedPage && savedPage !== '/homePageClient') {
        contentFrame.src = savedPage;

        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            const linkSrc = link.getAttribute('data-src');
            if (linkSrc === savedPage) {
                navLinks.forEach(l => l.classList.remove('active'));
                link.classList.add('active');
            }
        });
    }
});